package com.tpyule.tpclass.service.impl;

import com.tpyule.tpclass.dao.UserDao;
import com.tpyule.tpclass.entity.bean.FailResultBean;
import com.tpyule.tpclass.entity.bean.ResultBean;
import com.tpyule.tpclass.entity.bean.SuccessResultBean;
import com.tpyule.tpclass.entity.bo.*;
import com.tpyule.tpclass.entity.dto.CommonQueryDto;
import com.tpyule.tpclass.entity.dto.StudentQueryDto;
import com.tpyule.tpclass.entity.dto.UserBindDto;
import com.tpyule.tpclass.entity.dto.UserListQueryDto;
import com.tpyule.tpclass.entity.pojo.*;
import com.tpyule.tpclass.service.RoleService;
import com.tpyule.tpclass.service.SubscriptionService;
import com.tpyule.tpclass.service.UserService;
import com.tpyule.tpclass.service.WebService;
import com.tpyule.tpclass.util.MD5Util;
import com.tpyule.tpclass.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zzz
 * @date 2020/2/21 0021 下午 4:33
 */
@Service
public class  UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    RoleService roleService;
    @Autowired
    SubscriptionService subscriptionService;
    @Autowired
    WebService webService;

    @Override
    public User getUserByPhoneOrEmail(String str) {
        return userDao.getUserByPhoneOrEmail(str);
    }

    @Transactional
    @Override
    public void addUser(User user) {
        //用户ID
        user.setUserId(UUID.randomUUID().toString().toUpperCase());
        //用户盐：随机十位数
        user.setSalt(RandomUtil.getRandomStr(10));
        //加密密码
        String encodePassword= MD5Util.getMd5(user.getPassword()+user.getSalt(),2);
        user.setNickname("学员"+(int)(Math.random()*10000));
        user.setGender(0);
        user.setOffice("学生");
        user.setImageUrl("http://cdn.404zz.cn/course/image/20200507233648FTHCVH.jpg");
        user.setSignature("");
        user.setPassword(encodePassword);
        user.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        userDao.addUser(user);
        subscriptionService.addSubscriptionConfig(user.getUserId());
        Web web=webService.getWeb(1);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(web.getNewUserRole());
        roleService.addUserRole(userRole);
    }

    @Override
    public boolean updateUser(User user) {
        int result = userDao.updateUser(user);
        if(result!=0){
            return true;
        } else {
            return false;
        }
    }

    @Override
    public ResultBean userBindingUpdate(UserBindDto userBindDto) {
        ResultBean resultBean = null;
        if(userBindDto.getUserId()==null||"".equals(userBindDto.getUserId())){
            resultBean= new FailResultBean("数据传输异常");
        }else {
            switch (userBindDto.getType()){
                case 1:{
                    User user = userDao.getUserByPhoneOrEmail(userBindDto.getEmail());
                    if(user==null){
                        User updateUser = new User();
                        updateUser.setUserId(userBindDto.getUserId());
                        updateUser.setEmail(userBindDto.getEmail());
                        int result = userDao.updateUser(updateUser);
                        resultBean = new SuccessResultBean<String>(userBindDto.getEmail(),"更新成功");
                    } else {
                        resultBean = new FailResultBean("该邮箱已被绑定至其他用户");
                    }
                    break;
                }
                case 2:{
                    User user = userDao.getUserByPhoneOrEmail(userBindDto.getPhone());
                    if(user==null){
                        User updateUser = new User();
                        updateUser.setUserId(userBindDto.getUserId());
                        updateUser.setPhone(userBindDto.getPhone());
                        int result = userDao.updateUser(updateUser);
                        if (result!=0) {
                            resultBean = new SuccessResultBean<String>(userBindDto.getPhone(),"更新成功");
                        } else {
                            resultBean = new FailResultBean("更新失败");
                        }
                    } else {
                        resultBean = new FailResultBean("该手机号已被绑定至其他用户");
                    }
                    break;
                }
                case 3:{
                    User user = userDao.getUserById(userBindDto.getUserId());
                    if(user!=null){
                        String encodePassword= MD5Util.getMd5(userBindDto.getOldPassword()+user.getSalt(),2);
                        if(user.getPassword().equals(encodePassword)){
                            User updateUser = new User();
                            updateUser.setUserId(user.getUserId());
                            updateUser.setPassword(MD5Util.getMd5(userBindDto.getNewPassword()+user.getSalt(),2));
                            int result = userDao.updateUser(updateUser);
                            if(result!=0){
                                resultBean = new SuccessResultBean("更新成功");
                            }else {
                                resultBean = new FailResultBean("更新失败");
                            }
                        }else{
                            resultBean=new FailResultBean("旧密码错误");
                        }
                    }else{
                        resultBean=new FailResultBean<>("该用户不存在");
                    }
                    break;
                }
                case 4:{
                    User user = userDao.getUserById(userBindDto.getUserId());
                    if(user!=null){
                        String encodePassword= MD5Util.getMd5(userBindDto.getOldPassword()+user.getSalt(),2);
                        if(user.getPassword().equals(encodePassword)){
                            resultBean = new SuccessResultBean("验证成功");
                        }else{
                            resultBean=new FailResultBean("旧密码错误");
                        }
                    }else{
                        resultBean=new FailResultBean<>("该用户不存在");
                    }
                    break;
                }
                default:
                    resultBean = new FailResultBean("类型错误");
            }
        }
        return resultBean;
    }

    @Override
    public List<NewUserBo> getNewUser(int day) {
        return userDao.getNewUser(day);
    }

    @Override
    public int getSizeUser(UserListQueryDto dto) {
        return userDao.getSizeUser(dto);
    }

    @Override
    public List<UserListBo> getListUser(UserListQueryDto dto) {
        if(dto.getPage()>0&&dto.getPageSize()>0){
            dto.setStart((dto.getPage() - 1) * dto.getPageSize());
        }
        return userDao.getListUser(dto);
    }

    @Override
    public List<StudentAnaBo> getAnaUser(StudentQueryDto dto) {
        if(dto.getPage()>0&&dto.getPageSize()>0){
            dto.setStart((dto.getPage() - 1) * dto.getPageSize());
        }
        return userDao.getAnaUser(dto);
    }

    @Override
    public int getSizeAnaUser(StudentQueryDto dto) {
        return userDao.getSizeAnaUser(dto);
    }

    @Override
    public UserDetailBo getDetailUser(String userId) {
        List<Role> roles = roleService.getRoleByUserId(userId);
        int[] roleIds = new int[roles.size()];
        for (int i = 0; i < roles.size(); i++) {
            roleIds[i] = roles.get(i).getId();
        }
        UserDetailBo bo = userDao.getDetailUser(userId);
        bo.setRoleIds(roleIds);
        return bo;
    }

    @Override
    public int resetPassword(User user) {
        User u = userDao.getUserById(user.getUserId());
        String encodePassword = MD5Util.getMd5(user.getPassword()+u.getSalt(),2);
        u.setPassword(encodePassword);
        return userDao.updateUser(u);
    }

    @Override
    public User getUserById(String userId) {
        return userDao.getUserById(userId);
    }

    @Transactional
    @Override
    public int addApprove(Approve approve) {
        ApproveDetailBo bo = userDao.getDetailApproveByUId(approve.getUserId());
        if(bo!=null){
            Approve a = new Approve();
            a.setApproveId(bo.getApproveId());
            a.setRemove(0);
            userDao.updateApprove(a);
        }
        return userDao.addApprove(approve);
    }

    @Transactional
    @Override
    public int updateApprove(Approve approve) {
        if (approve.getState()==2){
            ApproveDetailBo approveDetailBo = userDao.getDetailApprove(approve.getApproveId());
            User user = userDao.getUserById(approveDetailBo.getUserId());
            user.setOffice(approveDetailBo.getOffice());
            userDao.updateUser(user);
            List<Role> roles = roleService.getRoleByUserId(user.getUserId());
            // 判断是否有教师角色
            Boolean hasT = false;
            for (Role role : roles) {
                if (role.getId() == 19){
                    hasT = true;
                    break;
                }
            }
            if (!hasT){
                UserRole userRole = new UserRole();
                // 添加教师角色
                userRole.setRoleId(19);
                userRole.setUserId(user.getUserId());
                roleService.addUserRole(userRole);
            }
        }
        return userDao.updateApprove(approve);
    }

    @Override
    public List<ApproveListBo> getListApprove(CommonQueryDto dto) {
        if(dto.getPage()>0&&dto.getPageSize()>0){
            dto.setStart((dto.getPage() - 1) * dto.getPageSize());
        }
        return userDao.getListApprove(dto);
    }

    @Override
    public int getSizeApprove() {
        return userDao.getSizeApprove();
    }

    @Override
    public ApproveDetailBo getDetailApprove(int approveId) {
        return userDao.getDetailApprove(approveId);
    }

    @Override
    public ApproveDetailBo getDetailApproveByUId(String userId) {
        return userDao.getDetailApproveByUId(userId);
    }

    @Override
    public List<AnaBoTwo> getAnaSex() {
        return userDao.getAnaSex();
    }

    @Override
    public List<AnaBoTwo> getAnaOffice() {
        List<UserDetailBo> users = userDao.getAllUser();
        List<AnaBoTwo> anaBoTwos = new ArrayList<>();
        String[] offices = new String[]{"学生","Python工程师", "Web前端工程师", "JS工程师","PHP开发工程师","JAVA开发工程师","移动开发工程师","Linux系统工程师","产品经理", "数据库工程师","软件工程师","UI设计师","交互设计师","CG影视动画师","全栈工程师","算法工程师","架构"};
        for (String office : offices) {
            AnaBoTwo anaBoTwo = new AnaBoTwo();
            anaBoTwo.setName(office);
            anaBoTwo.setValue(0);
            anaBoTwos.add(anaBoTwo);
        }
        for (UserDetailBo user : users) {
            for (AnaBoTwo anaBoTwo : anaBoTwos) {
                if (anaBoTwo.getName().equals(user.getOffice())){
                    anaBoTwo.setValue(anaBoTwo.getValue()+1);
                    break;
                }
            }
        }

        Iterator<AnaBoTwo> it = anaBoTwos.iterator();
        while(it.hasNext()){
            AnaBoTwo anaBoTwo = it.next();
            if(anaBoTwo.getValue()==0){
                it.remove();
            }
        }
        return anaBoTwos;
    }
}
